// page/component/test/test.js
Page({

  data: {
    toView: 'all',
    toViewLeft: [],
    toViewRight: [],
    list: [],
    isOrders: true,
    isHeader: [],
    userID: null
  },

  onLoad: function (query) {
    let num = query.num;
    console.log(num);
    let setState = ''; 
    this.setData({
      toView: num
    });
    switch (num) {
      case 'payment':
        setState = '1';
        break;
      case 'deliver':
        setState = '2';
        break;
      case 'receipt':
        setState = '3';
        break;
      case 'evaluation':
        setState = '4';
        break;
      case 'afterSale':  
        setState = '5';
    }
    console.log(setState);
    let that = this;
    wx.getStorage({
      key: 'userID',
      success(res) {
        that.setData({
          userID: res.data
        }) 
      }
    });
    let userId = this.data.userID;
    if (userId == null) {
      userId = getApp().globalData.userID
    } 
    let Url = 'https://localhost:80/order/queryByUser/'+ userId +'/' + setState;
    // let Url = 'http://192.168.1.186/order/queryByUser/3/' + setState;
    console.log(Url);
    wx.request({
      url: Url,
      header: {
        'content-type': 'application/json'
      },
      success(res) { 
        console.log(res);
        console.log('---------------==================');
        let viewLeft = [];
        let viewRight = [];
        let isHead = [];
        let number = res.data.rows.length;
        for (let i = 0; i < number; i++) {
          if (res.data.rows[i].orderDetails.length < 4) {
            viewLeft[i] = false;  
            viewRight[i] = false;
          } else {   
            viewLeft[i] = true;
            viewRight[i] = true;
          }
        }
        for (let i = 0; i < number; i++) {
          switch(res.data.rows[i].orderState)
          {
            case 1:
              isHead[i]='payment';
              break;
            case 2:
              isHead[i]='deliver';
              break;
            case 3:
              isHead[i]='receipt';
              break;
            case 4:
              isHead[i]='evaluation';
              break;
            case 5:
              isHead[i]='afterSale';
          }
          let lengths = res.data.rows[i].orderDetails.length;
          let n = i;
          for(let j = 0; j < lengths; j++) 
          {
            let arr = [];
            let str = res.data.rows[n].orderDetails[j].goods.goodsImg;
            arr = str.split(',');
            console.log(arr);
            res.data.rows[n].orderDetails[j].goods.goodsImg = arr[0];
          }
          let box = [];
          let boxId = res.data.rows[i].orderAddress;
          box = boxId.split('/');
          res.data.rows[i].orderBoxId = box[1];
          let date = res.data.rows[i].orderDate;
          let isIos = 0;
          wx.getSystemInfo({
            success (res) {
              console.log(res.system);
              let arr = res.system.split(' ');
              if (arr[0] == 'iOS') {
                isIos = 1;
              }
              console.log(arr[0]);
            }
          })
          let timer;
          if (isIos == 0) {
            console.log('anzhuo');
            console.log(date);
            timer = new Date(date);
            let y = timer.getFullYear();
            let m = timer.getMonth()+1;
            let d = timer.getDate();
            let h = timer.getHours();
            let mm = timer.getMinutes();
            let s = timer.getSeconds();
            console.log(m);
            timer = y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s;
          } else {
            console.log('ios');
            console.log(date);            
            let arr = date.split('T');
            let dt = arr[0];
            let darr = dt.split('-');
            let t = arr[1];
            let tarr = t.split('.000');
            let marr = tarr[0].split(':');
            marr[0] = parseInt(marr[0]);
            darr[2] = parseInt(darr[2]);
            console.log(typeof(darr[2]));
            marr[0] = marr[0] + 8;
            if (marr[0] >= 24) {
              marr[0] = marr[0]%24;
              darr[2] = darr[2]+1;
            }
            timer = parseInt(darr[0]) + '-' + parseInt(darr[1]) + '-' + parseInt(darr[2]) + ' ' + marr[0] + ':' + parseInt(marr[1]) + ':' + parseInt(marr[2]);            
            console.log(timer);
          }
          console.log('-------------------------------------------------------------------------------------------');
          console.log(date);
          console.log(timer);
          console.log('-------------------------------------------------------------------------------------------');
          res.data.rows[i].orderDate = timer
          let area = res.data.rows[i].orderBoxId
          if (area.indexOf('xd') >= 0) {
            res.data.rows[i].takeAddr = '13号楼前广场'
          } else if (area.indexOf('xx') >= 0) {
            res.data.rows[i].takeAddr = '13号楼前广场'
          } else if (area.indexOf('wk3') >= 0) {
            res.data.rows[i].takeAddr = '北门优度客'
          } else {
            res.data.rows[i].takeAddr = '西门南轩洋果蔬店'
          }
          switch(res.data.rows[i].orderState)
          {
            case 1:
              isHead[i]='payment';
              break;
            case 2:
              isHead[i]='deliver';
              break;
            case 3:
              isHead[i]='receipt';
              break;
            case 4:
              isHead[i]='evaluation';
              break;
            case 5:
              isHead[i]='afterSale';
          }
        }
        let isSure = true;
        if (number==0) {
          isSure = false
        }
        that.setData({
          list: res.data.rows,
          isOrders: isSure,
          toViewLeft: viewLeft,
          toViewRight: viewRight,
          isHeader: isHead
        }); 
        console.log('ok');
        console.log(that.data.isHeader);
        console.log(that.data.list);
      }
    });
  },

  toViewClick: function (e) { 
    let toUrl = e.currentTarget.dataset.hash;
    let setState = '';
    let that = this;
    this.setData({
      toView: toUrl 
    })
    switch (toUrl) {
      case 'payment':
        setState = '1';
        break;
      case 'deliver':
        setState = '2';
        break;
      case 'receipt':
        setState = '3';
        break;
      case 'evaluation':
        setState = '4';
        break;
      case 'afterSale':
        setState = '5';
    }
    wx.getStorage({
      key: 'userID',
      success(res) {
        that.setData({
          userID: res.data
        }) 
      }
    });
    let userId = this.data.userID;
    if (userId == null) {
      userId = getApp().globalData.userID
    }
    let Url = 'https://localhost:80/order/queryByUser/' + userId + '/' + setState;
    console.log(Url); 
    wx.request({
      url: Url,
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log(res);
        let viewLeft = [];
        let viewRight = [];
        let isHead = [];
        let number = res.data.rows.length;
        for (let i = 0; i < number; i++) {
          if (res.data.rows[i].orderDetails.length < 4) {
            viewLeft[i] = false;
            viewRight[i] = false;
          } else {
            viewLeft[i] = true;
            viewRight[i] = true;
          }
        }
        for (let i = 0; i < number; i++) {
          switch(res.data.rows[i].orderState)
          {
            case 1:
              isHead[i]='payment';
              break;
            case 2:
              isHead[i]='deliver';
              break;
            case 3:
              isHead[i]='receipt';
              break;
            case 4:
              isHead[i]='evaluation';
              break;
            case 5:
              isHead[i]='afterSale';  
          }
          let lengths = res.data.rows[i].orderDetails.length;
          let n = i;
          for(let j = 0; j < lengths; j++) 
          {
            let arr = [];
            let str = res.data.rows[n].orderDetails[j].goods.goodsImg;
            arr = str.split(',');
            console.log(arr);
            res.data.rows[n].orderDetails[j].goods.goodsImg = arr[0];
          }
          let box = [];
          let boxId = res.data.rows[i].orderAddress;
          box = boxId.split('/');
          console.log(box[1]);
          res.data.rows[i].orderBoxId = box[1];
          console.log(res.data.rows[i]);
          let date = res.data.rows[i].orderDate;
          let isIos = 0;
          wx.getSystemInfo({
            success (res) {
              console.log(res.system);
              let arr = res.system.split(' ');
              if (arr[0] == 'iOS') {
                isIos = 1;
              }
              console.log(arr[0]);
            }
          })
          let timer;
          if (isIos == 0) {
            console.log('anzhuo');
            console.log(date);
            timer = new Date(date);
            let y = timer.getFullYear();
            let m = timer.getMonth()+1;
            let d = timer.getDate();
            let h = timer.getHours();
            let mm = timer.getMinutes();
            let s = timer.getSeconds();
            console.log(m);
            timer = y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s;
          } else {
            console.log('ios');
            console.log(date);            
            let arr = date.split('T');
            let dt = arr[0];
            let darr = dt.split('-');
            let t = arr[1];
            let tarr = t.split('.000');
            let marr = tarr[0].split(':');
            marr[0] = parseInt(marr[0]);
            darr[2] = parseInt(darr[2]);
            console.log(typeof(darr[2]));
            marr[0] = marr[0] + 8;
            if (marr[0] >= 24) {
              marr[0] = marr[0]%24;
              darr[2] = darr[2]+1;
            }
            timer = parseInt(darr[0]) + '-' + parseInt(darr[1]) + '-' + parseInt(darr[2]) + ' ' + marr[0] + ':' + parseInt(marr[1]) + ':' + parseInt(marr[2]);            
            console.log(timer);
          }
          res.data.rows[i].orderDate = timer
          let area = res.data.rows[i].orderBoxId
          if (area.indexOf('xd') >= 0) {
            res.data.rows[i].takeAddr = '13号楼前广场'
          } else if (area.indexOf('xx') >= 0) {
            res.data.rows[i].takeAddr = '13号楼前广场'
          } else if (area.indexOf('wk3') >= 0) {
            res.data.rows[i].takeAddr = '北门优度客'
          } else {
            res.data.rows[i].takeAddr = '西门南轩洋果蔬店'
          }
        }
        let isSure = true;
        if (number==0) {
          isSure = false
        }
        that.setData({
          list: res.data.rows,
          isOrders: isSure,
          toViewLeft: viewLeft,
          toViewRight: viewRight,
          isHeader: isHead
        }); 
        console.log('ok');
        console.log(that.data.isHeader);
        console.log(res.data.list);
      }
    });
  },

  scroll: function (e) {
    let number = e.currentTarget.dataset.index;
    let ViewLeft = 'toViewLeft[' + number + ']';
    let ViewRight = 'toViewRight[' + number + ']';
    this.setData({
      [ViewLeft]: false,
      [ViewRight]: false
    })
  },

  scrollLeft: function (e) {
    let number = e.target.dataset.index; 
    let ViewRight = 'toViewRight[' + number + ']';
    this.setData({
      [ViewRight]: true
    });
  },

  scrollRight: function (e) {
    let number = e.target.dataset.index;   
    let ViewLeft = 'toViewLeft[' + number + ']';
    this.setData({
      [ViewLeft]: true
    });
  },  

  afterSale (e) {
    console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index;
    console.log(this.data.list[index]);
    wx.navigateTo({
      url: '../aftersale/aftersale?data=' + JSON.stringify(this.data.list[index])
    })
  },

  evaluate (e) {
    console.log(e);
    let hash = e.currentTarget.dataset.hash;
    console.log(this.data.list[hash]);
    let Url = '../evaluate/evaluate?num=' + JSON.stringify(this.data.list[hash]);
    wx.navigateTo({
      url: Url
    })  
  },

  again () {
    wx.switchTab({
      url: '../category/category'
    })
  },

  sureOrder (e) {
    let index = e.currentTarget.dataset.index;
    console.log(this.data.list[index].orderId);
    let orderId = this.data.list[index].orderId;
    let list = this.data.list;
    wx.request({
      url: 'https://localhost:80/order/changeOrderStatus', 
      data: {
        orderId: orderId,
        orderState: '4'
      },
      method : 'POST',
      success: function (res) {
        console.log('成功');
        wx.showToast({
          title: '订单已确认',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        console.log('请求失败！');
        wx.showToast({
          title: '订单确认失败',
          icon: 'cancel',
          duration: 2000
        })
      }
    })  
    list.splice(index, 1);
    console.log(list);
    this.setData({
      list: list
    })
  },

  toPay (e) {
    let index = e.currentTarget.dataset.index;
    console.log(index);
    console.log(this.data.list[index]);
    function Details (detailNum, detailPrice, detailGoods) {
      this.detailNum = detailNum;
      this.detailPrice = detailPrice;
      this.detailGoods = detailGoods;
    }
    const goodsImg = [];
    const orders = [];
    let n = 0;
    console.log(this.data.carts)
    console.log(orders);
    for (let i = 0; i < this.data.list[index].orderDetails.length; i++)
    {
      goodsImg[n] = this.data.list[index].orderDetails[i].goods.goodsImg;
      let detailNum = this.data.list[index].orderDetails[i].detailNum;
      let detailPrice = this.data.list[index].orderDetails[i].detailNum * this.data.list[index].orderDetails[i].detailPrice;
      detailPrice = detailPrice.toFixed(2);
      let detailGoods = this.data.list[index].orderDetails[i].goods.goodsId;
      orders[i] = new Details(detailNum, detailPrice, detailGoods)
      n++
    }
    let order = [];
    order = JSON.stringify(orders);
    console.log(order);
    wx.setStorage({
      key: 'details',
      data: order
    })
    console.log(order);
    wx.setStorage({
      key: 'price',
      data: this.data.list[index].orderPrice
    })
    wx.setStorage({
      key: 'imgs',
      data: goodsImg
    })
    wx.navigateTo({
      url: '../orders/orders'
    })
  }, 

  cancelOrder (e) {
    let hash = e.currentTarget.dataset.hash;
    console.log(hash);
    console.log(this.data.list[hash]);
    let that = this;
    let list = this.data.list;
    
    wx.request({
      url: 'https://localhost:80/order/delete/' + that.data.list[hash].orderId, 
      method : 'POST',
      success: function (res) {
        console.log('成功');
        wx.showToast({
          title: '订单取消成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        console.log('请求失败！');
        wx.showToast({
          title: '订单取消失败',
          icon: 'cancel',
          duration: 2000
        })
      }
    })  
    list.splice(hash, 1);
    console.log(list);
    this.setData({
      list: list
    })
  },

  orderDetail (e) {
    let num = e.currentTarget.dataset.index;
    console.log(num);
    console.log(this.data.list[num]);
    wx.navigateTo({
      url: '../orderDetail/orderDetail?data=' + JSON.stringify(this.data.list[num])
    })
  },

  onUnload: function () {
    wx.switchTab({
      url: '../person/person'
    })
  },
})

